package zz.app.jmhviewer;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import zz.app.jmhviewer.JMH.JMHCssData;
import zz.app.jmhviewer.JMH.JMHHtmlData;
import zz.app.jmhviewer.JMH.JMHHtmlKashiData;
import zz.app.jmhviewer.JMH.JMHJsonData;
import zz.app.jmhviewer.JMH.JMHKana;
import zz.app.jmhviewer.JMH.JMHUtils;

public class ShowActivity extends AppCompatActivity {

    private static final String TAG = "TAG";
    JMHJsonData data;
    String host;
    GetHtmlCssTask getHtmlCssTask;
    GetPicDataTask getPicDataTask1,getPicDataTask2;
    TextView tvTitle,tvArtist;
    LinearLayout jmhKashiLayout;
    KashiScrollView kashiScrollView;
    RelativeLayout musicPlayerLayout;
    TextView tvTime;
    Drawable bkgnd;
    JMHCssData cssData;
    JMHHtmlData htmlData;
    View contentView;
    MediaPlayer mediaPlayer;
    Timer playerTimer;
    Handler handler;
    KashiView lastView,currentView;
    Button btnPlayPause;
    SeekBar seekBar;
    boolean bSeeking=false;
    boolean bPrepared=false;
    boolean bHideMusicPlayer =false;
    long totalTime;
    String bkgndVert,bkgndHori;
    String name;
    private boolean bTimerPause;
    KashiView slideTempView;
    Button btnOrientation;
    TextView tvloading;
    private float[] fontsizeScale=new float[]{0.7f,0.8f,0.9f,1f,1.1f,1.2f,1.3f};
    private int fontsizeScaleIndex=3;
    private int time=0;
    private AudioNoisyBoardcastReceiver audioNoisyBoardcastReceiver;



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        contentView=getLayoutInflater().inflate(R.layout.activity_show,null);
        setContentView(contentView);
        handler=new Handler();
        tvTitle=findViewById(R.id.tvtitle);
        tvArtist=findViewById(R.id.tvartist);
        tvloading=findViewById(R.id.tvloading);
        jmhKashiLayout=findViewById(R.id.jmhkashilayout);
        kashiScrollView=findViewById(R.id.kashiscrollview);
        kashiScrollView.setHandler(handler);
        musicPlayerLayout=findViewById(R.id.musicplayer);
        tvTime =findViewById(R.id.tvTime);
        seekBar=findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(bSeeking) {
                    time= (int) (progress * totalTime / 100);
                    resetKashi();
                    tvTime.setText(timeToString(time));
                    scrollKashiDirectly(time);
                    updateKashi();
                    }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if(!bSeeking) {
                    bSeeking = true;
                    bTimerPause=true;
                }

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(bSeeking) {
                    bSeeking = false;
                    bTimerPause=false;
                    mediaPlayer.seekTo((int) (seekBar.getProgress()*totalTime/100));

                }
            }
        });
        btnOrientation=findViewById(R.id.btnOrientation);
        btnOrientation.setOnClickListener(v->{
            if(Utils.isScreenOriatationPortrait(ShowActivity.this)){
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            }else{
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });
        btnPlayPause=findViewById(R.id.btnPlayPause);
        btnPlayPause.setOnClickListener(v -> {
            if(bPrepared){
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                    btnPlayPause.setBackgroundResource(R.drawable.playdrawable);
                }else{
                    mediaPlayer.start();
                    btnPlayPause.setBackgroundResource(R.drawable.pausedrawable);
                }
            }
        });
        kashiScrollView.setOnClickListener(v -> {
            if(!bHideMusicPlayer){
                bHideMusicPlayer =true;
                musicPlayerLayout.setVisibility(View.GONE);
            }else{
                bHideMusicPlayer =false;
                musicPlayerLayout.setVisibility(View.VISIBLE);
            }
        });
        kashiScrollView.setOnScrollScaleListener(big -> {
            if(big){
                Log.i(TAG, "onCreate: BIG");
                fontsizeScaleIndex++;
                if(fontsizeScaleIndex>6)fontsizeScaleIndex=6;
            }else{
                Log.i(TAG, "onCreate: SMALL");
                fontsizeScaleIndex--;
                if(fontsizeScaleIndex<0)fontsizeScaleIndex=0;

            }

            handler.post(() -> scrollKashiDirectly(time));
            update(fontsizeScaleIndex);
        });
        kashiScrollView.setSmoothScrollingEnabled(true);

        musicPlayerLayout.setBackgroundColor(Color.parseColor("#7fffffff"));
        data=(JMHJsonData)getIntent().getSerializableExtra("jsonData");
        name=data.name;
        host=getIntent().getStringExtra("host");
        getHtmlCssTask =new GetHtmlCssTask(this, () -> {
            cssData= getHtmlCssTask.getCssData();
            htmlData= getHtmlCssTask.getHtmlData();
            if(cssData!=null&&htmlData!=null) {
            update(fontsizeScaleIndex);
                        if(Utils.isScreenOriatationPortrait(ShowActivity.this)){
                            if(getPicDataTask1==null) {
                                getPicDataTask1 = new GetPicDataTask(ShowActivity.this, () -> {
                                    bkgndVert = getPicDataTask1.getPicData();
                                    if(Utils.isScreenOriatationPortrait(ShowActivity.this)) {
                                        if (bkgndVert != null) {
                                            bkgnd = new BitmapDrawable(null, bkgndVert);
                                            contentView.setBackground(bkgnd);
                                        }
                                    }
                                });
                                getPicDataTask1.execute(host, name, "vert");
                            }

                        }else {
                                if (getPicDataTask2 == null) {
                                    getPicDataTask2 = new GetPicDataTask(ShowActivity.this, () -> {
                                        bkgndHori = getPicDataTask2.getPicData();
                                        if(!Utils.isScreenOriatationPortrait(ShowActivity.this)) {
                                            if (bkgndHori != null) {
                                                bkgnd = new BitmapDrawable(null, bkgndHori);
                                                contentView.setBackground(bkgnd);
                                            }
                                        }
                                    });
                                    getPicDataTask2.execute(host, name, "hori");
                                }
                            }

                mediaPlayer=new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(JMHUtils.getMusicPath(host,name));
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnBufferingUpdateListener((mp, percent) -> seekBar.setSecondaryProgress(percent));
                    mediaPlayer.setOnCompletionListener(mp -> {
                        seekBar.setProgress(0);
                        tvTime.setText(getResources().getText(R.string.inittime));
                        btnPlayPause.setBackgroundResource(R.drawable.playdrawable);
                    });
                    mediaPlayer.setOnPreparedListener(mp -> {
                        if (mediaPlayer != null) {
                            audioNoisyBoardcastReceiver=new AudioNoisyBoardcastReceiver(() -> {
                                if(mediaPlayer.isPlaying()){
                                    mediaPlayer.pause();
                                    btnPlayPause.setBackgroundResource(R.drawable.playdrawable);
                                }
                            });
                            registerReceiver(audioNoisyBoardcastReceiver,new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
                            bPrepared = true;
                            tvloading.setVisibility(View.INVISIBLE);
                            totalTime = mediaPlayer.getDuration();
                            playerTimer = new Timer();
                            playerTimer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    if (!bTimerPause) {
                                        handler.post(() -> {
                                            if (mediaPlayer != null) {
                                                time = mediaPlayer.getCurrentPosition();
                                                if (mediaPlayer.isPlaying()) {
                                                    currentView = findKashiViewByTime(time);
                                                    if(currentView==null){
                                                        resetKashi();

                                                    }
                                                    if (lastView != currentView) {
                                                        if (lastView != null)
                                                            lastView.setFlag(KashiView.FLAG_OUT_ANIM);
                                                        if (currentView != null) {
                                                            if(slideTempView!=null&&slideTempView==currentView)slideTempView=null;
                                                            else currentView.setFlag(KashiView.FLAG_IN_ANIM);
                                                        }
                                                        lastView = currentView;
                                                    }
                                                    if (!bSeeking) {
                                                        tvTime.setText(timeToString(time));
                                                        seekBar.setProgress((int) (time  * 100 / totalTime));
                                                    }
                                                }
                                            }
                                            updateKashi();

                                        });

                                    }
                                }
                            }, 0, 50);
                            mediaPlayer.start();
                            btnPlayPause.setBackgroundResource(R.drawable.pausedrawable);

                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }else{
                Toast.makeText(ShowActivity.this,"请检查网络状态！",Toast.LENGTH_LONG).show();
            }
        });

        getHtmlCssTask.execute(host,name);

    }

    private void scrollKashiDirectly(int time) {
        slideTempView = findKashiViewByTime(time);
        if (slideTempView != null) {
            kashiScrollView.scrollTo(kashiScrollView.getLeft(), slideTempView.getTop() - kashiScrollView.getHeight() / 2 + slideTempView.getHeight() / 2);
            slideTempView.setFlag(KashiView.FLAG_IN_FORCE);
        }
    }


    private CharSequence timeToString(long currentpos) {
        long time=currentpos/1000;
        long minute=time/60;
        long second=time%60;
        return String.format(Locale.getDefault(),"%2d:%02d",minute,second);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setBkgndPic(){
        if(contentView!=null) {
            if (Utils.isScreenOriatationPortrait(ShowActivity.this)) {
                if (getPicDataTask1 == null) {
                    getPicDataTask1 = new GetPicDataTask(ShowActivity.this, () -> {
                        bkgndVert = getPicDataTask1.getPicData();
                        if (bkgndVert != null) {
                            bkgnd = new BitmapDrawable(null, bkgndVert);
                            setBkgndPic();
                        }
                    });
                    getPicDataTask1.execute(host, name, "vert");
                }
                if (bkgndVert != null) {
                    bkgnd = new BitmapDrawable(null, bkgndVert);
                    contentView.setBackground(bkgnd);
                }
            } else {
                if (getPicDataTask2 == null) {
                    getPicDataTask2 = new GetPicDataTask(ShowActivity.this, () -> {
                        bkgndHori = getPicDataTask2.getPicData();
                        if (bkgndHori != null) {
                            bkgnd = new BitmapDrawable(null, bkgndHori);
                            setBkgndPic();
                        }
                    });
                    getPicDataTask2.execute(host, name, "hori");
                }
                if (bkgndHori != null) {
                    bkgnd = new BitmapDrawable(null, bkgndHori);
                    contentView.setBackground(bkgnd);
                }
            }

            handler.postDelayed(() -> {
                if (currentView != null) {
                    currentView.orientationChanged();
                }
            }, 100);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void update(int fontIndex){
        if(contentView!=null) {
            if (cssData != null && htmlData != null) {
                contentView.setBackgroundColor(cssData.backgroundColor);
                tvTitle.setText(htmlData.title);
                tvTitle.setTextSize(cssData.titleSize);
                tvTitle.setTextColor(cssData.titleColor);
                tvArtist.setText(htmlData.artist);
                tvArtist.setTextSize(cssData.artistSize);
                tvArtist.setTextColor(cssData.artistColor);
                jmhKashiLayout.removeAllViews();
                boolean vert = Utils.isScreenOriatationPortrait(ShowActivity.this);
                for (int i = 0; i < htmlData.kashiData.size(); i++) {
                    JMHHtmlKashiData data = htmlData.kashiData.get(i);
                    KashiView view = new KashiView(ShowActivity.this);
                    if (vert) {
                        view.setVertScale();
                    } else {
                        view.setHoriScale();
                    }
                    view.setFontSizeScale(fontsizeScale[fontIndex]);
                    view.setHandler(handler);
                    view.setKashi(data.kashi);
                    view.setKashiSize(cssData.kashiSize);
                    view.setKashiColor(cssData.kashiColor);
                    view.setCurrentKashiColor(cssData.currentKashiColor);
                    view.setCurrentKashiSize(cssData.currentKashiSize);
                    view.setKanaColor(cssData.kanaColor);
                    view.setTranslate(data.translate);
                    view.setTranslateColor(cssData.translateColor);
                    view.setTranslateSize(cssData.translateSize);
                    view.setCurrentTranslateSize(cssData.currentTranslateSize);
                    view.setAnimeTime(cssData.animeTime);
                    for (JMHKana kana : data.kanas) {
                        view.addKana(kana);
                    }
                    view.fresh();
                    jmhKashiLayout.addView(view);
                }
            }
            setBkgndPic();
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        update(fontsizeScaleIndex);
    }
    private void resetKashi(){
        int cnt=jmhKashiLayout.getChildCount();
        for(int i=0;i<cnt;i++) {
            KashiView v = (KashiView) jmhKashiLayout.getChildAt(i);
            v.setFlag(KashiView.FLAG_DEFAULT);

        }
    }
    private void updateKashi(){
        int cnt=jmhKashiLayout.getChildCount();
        for(int i=0;i<cnt;i++) {
            KashiView v = (KashiView)jmhKashiLayout.getChildAt(i);
            v.update();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(getHtmlCssTask!=null){
            getHtmlCssTask.cancel(true);
        }
        if(mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
        if(playerTimer!=null){
            playerTimer.cancel();
            playerTimer=null;
        }
        if(audioNoisyBoardcastReceiver!=null){
            unregisterReceiver(audioNoisyBoardcastReceiver);
            audioNoisyBoardcastReceiver=null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }
    private KashiView findKashiViewByTime(int time){
        ArrayList<JMHHtmlKashiData> data=htmlData.kashiData;
        int count=data.size();

        for(int i=0;i<count-1;i++) {
            int realtime=data.get(i).time*10;
            int realtime2=data.get(i+1).time*10;
           if(realtime<time&&realtime2>time){
               return (KashiView)jmhKashiLayout.getChildAt(i);
           }
        }
        int realtime=data.get(count-1).time*10;
        if(realtime<time){
            return (KashiView)jmhKashiLayout.getChildAt(count-1);
        }
        return null;
    }
}
